#!/usr/bin/python
import serial
import time

def main():
    try:
        # 打开串口
        ser = serial.Serial(port="/dev/ttyAMA0", baudrate=9600, timeout=1)
        print(ser.is_open)
        print("串口打开成功，开始监听数据...")
        print("按 Ctrl+C 退出")
        
        while True:
            # 读取数据
            if ser.in_waiting > 0:
                data = ser.read(ser.in_waiting)  # 读取所有可用数据
                print(f"接收到数据: {data}")
                print(f"十六进制: {data.hex()}")
                print(f"长度: {len(data)} 字节")
                
                # 尝试解析为字符串
                try:
                    text = data.decode('utf-8')
                    print(f"字符串: {text}")
                except:
                    print("无法解析为字符串")
                
                print("-" * 40)
            
            time.sleep(0.1)  # 短暂延时
            
    except serial.SerialException as e:
        print(f"串口错误: {e}")
    except KeyboardInterrupt:
        print("\n程序退出")
    finally:
        if 'ser' in locals() and ser.is_open:
            ser.close()
            print("串口已关闭")

if __name__ == "__main__":
    main() 